package com.example.demo4

import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PythonLanguage

class CompletionContributor : com.intellij.codeInsight.completion.CompletionContributor() {
    // 硬编码的补全规则：前缀 -> 补全项列表
    private val completionRules = mapOf(
            "seg" to listOf(
                    "InsertMarker(MYSTD.point(0, 2, 3))",
                    "InsertPolyline([MYSTD.point(0,2,3), MYSTD.point(1,5,3)])"
            ),
            "doc" to listOf(
                    "AddParagraph(\"文档段落\")",
                    "SetTitle(\"文档标题\")"
            )
    )

    init {
        extend(
                CompletionType.BASIC,
                PlatformPatterns.psiElement().withLanguage(PythonLanguage.INSTANCE),
                object : CompletionProvider<CompletionParameters>() {
                    override fun addCompletions(
                            parameters: CompletionParameters,
                            context: ProcessingContext,
                            result: CompletionResultSet
                    ) {
                        val element = parameters.position
                        val prevElement = element.prevSibling?.text ?: ""

                        // 触发条件：输入前缀后跟 "."
                        if (prevElement.endsWith(".")) {
                            val prefix = prevElement.dropLast(1) // 移除 "."
                            completionRules[prefix]?.forEach { item ->
                                result.addElement(
                                        LookupElementBuilder.create(item)
                                                .withTypeText("custom")
                                        //.withIcon(com.jetbrains.python.PythonIcons.Python.Python)
                                )
                            }
                        }
                    }
                }
        )
    }
}